﻿@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase
@{
    ViewBag.Title = "任务列表";

}
@section style{
    <!-- jqgrid-->
    <link href="~/Content/Css/plugins/jqgrid/ui.jqgrid.css" rel="stylesheet">
}

<div class="row-fluid clearfix bb-1 mb10" id="input_custom_searchbox">
    <div class="col-sm-5 pl0">
        <div class="input-group">
            <span class="input-group-addon">任务名称</span>
            <input type="text" class="form-control" id="txt_TaskName">
        </div>

    </div>
    <div class="col-sm-5  pl0">
        <div class="input-group">
            <span class="input-group-addon">创建时间</span>
            <div class="input-group col-sm-12 ">
                <input type="text" class="form-control col-sm-6  layer-date" name="start" id="txt_createStart" />
                <span class="input-group-addon" style="border-left:none; border-right:0;">到</span>
                <input type="text" class="form-control col-sm-6  layer-date" name="end" id="txt_createEnd" />
            </div>
        </div>
    </div>
    <div class="col-sm-2 pl0">
        <button class="btn btn-primary" id="btn_search">搜索</button>
    </div>
</div>

<!-- 查询条件 -->
<div class="searchbox"></div>

<div class="app-toolbar">
    <button class="btn btn-white btn-sm" id="btn_Add"><span class="fa fa-plus"></span> 添加任务</button>
    <button class="btn btn-white btn-sm" id="btn_Import_Template"><span class="fa fa-plus"></span> 批量添加任务</button>
    <button class="btn btn-white btn-sm" id="btn_refresh"><span class="fa fa-refresh"></span> 重新加载任务</button>
    <button class="btn btn-white btn-sm" id="btn_Export_Select"><span class="fa fa-file-excel-o"></span> 导出选中记录</button>
    <button class="btn btn-white btn-sm" id="btn_Export_All"><span class="fa fa-file-excel-o"></span> 导出所有记录</button>
</div>

<!-- 列表 -->
<table id="grid_Task"></table>

@section scripts{
    <!-- jqGrid -->
    <script src="~/Content/Scripts/plugins/jqgrid/i18n/grid.locale-cn.js"></script>
    <script src="~/Content/Scripts/plugins/jqgrid/jquery.jqGrid.min.js"></script>
    <script src="~/Content/Scripts/plugins/layer/laydate/laydate.js"></script>
    <script>
        var gridTask = null;
        $(function () {
            //初始化查询控件
            initSearchBox();

            //初始化数据
            initData();

            //事件绑定
            bindEvents();
        })

        //初始化搜索框
        function initSearchBox() {
            var options = {
                //查询事件
                "search": function (paramList) {
                    gridTask.load(handleParam(paramList));
                },
                //默认展开条件数
                "expandRow": 2,
                //查询条件
                "searchBoxs": [
                     {
                         "id": "Status",
                         "isMultiple": false,
                         "title": "任务状态",
                         "data": [
                             { "value": "0", "text": "运行" },
                             { "value": "1", "text": "停止" }
                         ]
                     }
                ]
            };
            $(".searchbox").search(options);

            //日期范围限制
            var start = {
                elem: '#txt_createStart',
                format: 'YYYY-MM-DD hh:mm:ss',
                max: laydate.now(),
                istime: true,
                istoday: true,
                choose: function (datas) {
                    end.min = datas; //开始日选好后，重置结束日的最小日期
                }
            };
            var end = {
                elem: '#txt_createEnd',
                format: 'YYYY-MM-DD hh:mm:ss',
                max: laydate.now(),
                istime: true,
                istoday: true,
                choose: function (datas) {
                    start.max = datas; //结束日选好后，重置开始日的最大日期
                }
            };
            laydate(start);
            laydate(end);
        }

        //初始化数据
        function initData() {
            var strEnabledHTML = '<a href="javascript:void(0)" class="action action-update pr10" title="编辑">编辑</a><a href="javascript:void(0)" class="action action-enabled pr10" title="运行任务">运行任务</a><a href="javascript:void(0)" class="action action-run pr10" title="立即运行">立即运行</a><a href="javascript:void(0)" class="action action-delete pr10" title="删除">删除</a>';
            var strDisabledHTML = '<a href="javascript:void(0)" class="action action-update pr10" title="编辑">编辑</a><a href="javascript:void(0)" class="action action-disabled pr10" title="停止任务">停止任务</a><a href="javascript:void(0)" class="action action-run pr10" title="立即运行">立即运行</a><a href="javascript:void(0)" class="action action-delete pr10" title="删除">删除</a>';

            //初始化表格控件
            gridTask = new Ywdsoft.Grid("grid_Task", {
                idField: "TaskID",
                height: calcGridHeight(),
                url: "/Task/PostQuery",
                multiselect: true,
                rownumbers: true,
                colNames: ['任务名称', '运行频率', '任务状态', '最近运行时间', "下次运行时间", '创建时间', '说明', '操作'],
                colModel: [
                     {
                         name: 'TaskName',
                         index: 'TaskName'
                     },

                    {
                        name: 'CronRemark',
                        index: 'CronRemark',
                        width: 100
                    },
                    {
                        name: 'StatusCn',
                        index: 'Status',
                        width: 100,
                        fixed: true,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var label_class = "";
                            switch (cellvalue) {
                                case "运行":
                                    label_class = "label-success";
                                    break;
                                case "停止":
                                    label_class = "label-warning";
                                    break;
                                default:
                                    break;
                            }
                            return "<span class='label {1}' title='{0}'>{0}</span>".format(cellvalue, label_class);
                        },
                    },
                    {
                        name: 'RecentRunTime',
                        index: 'RecentRunTime',
                        width: 150,
                        align: "center",
                        formatter: "date",
                        fixed: true,
                        formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s' }
                    },
                    {
                        name: 'LastRunTime',
                        index: 'LastRunTime',
                        width: 150,
                        align: "center",
                        formatter: "date",
                        fixed: true,
                        formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s' }
                    },
                    {
                        name: 'CreatedOn',
                        index: 'CreatedOn',
                        width: 150,
                        align: "center",
                        formatter: "date",
                        fixed: true,
                        formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s' }
                    },
                    {
                        name: 'Remark',
                        index: 'Remark',
                        sortable: false
                    },
                    {
                        sortable: false,
                        width: 200,
                        fixed: true,
                        title: false,
                        align: "center",
                        resizable: false,
                        formatter: function (cellvalue, options, rowObject) {
                            return '<div data-index="{0}">{1}</div>'.format(options.rowId, rowObject.Status == "1" ? strEnabledHTML : strDisabledHTML);
                        }
                    }]
            });

            //定时刷新
            //setInterval(function () {
            //    gridTask.reload();
            //}, 2000);
        }

        //计算表格高度
        function calcGridHeight() {
            return $(window).height() - 210;
        }

        //处理查询参数
        function handleParam(paramList) {
            var FilterList = [];
            //任务名称
            var strTaskName = $("#txt_TaskName").val().trim();
            if (strTaskName) {
                FilterList.push({ "Operator": "like", "FieldName": "TaskName", "FieldValue": strTaskName });
            }
            //创建时间
            var strCreateStart = $("#txt_createStart").val().trim();
            if (strCreateStart) {
                FilterList.push({ "Operator": "ge", "FieldName": "CreatedOn", "FieldValue": strCreateStart, "IsDateTime": true });
            }
            var strCreateEnd = $("#txt_createEnd").val().trim();
            if (strCreateEnd) {
                FilterList.push({ "Operator": "le", "FieldName": "CreatedOn", "FieldValue": strCreateEnd, "IsDateTime": true });
            }

            var item = null;
            var value = null;
            //时间范围
            for (var i = 0, length = paramList.length; i < length; i++) {
                item = paramList[i];
                value = null;
                switch (item.id) {
                    case "IsDisabled":
                        if (item.ValueList.length > 0) {
                            value = { "Operator": "eq", "FieldName": "IsDisabled", "FieldValue": item.ValueList.join(",") };
                            FilterList.push(value);
                        }
                        break;
                        //任务状态
                    case "Status":
                        if (item.ValueList.length > 0) {
                            value = { "Operator": "eq", "FieldName": "Status", "FieldValue": item.ValueList.join(",") };
                            FilterList.push(value);
                        }
                        break;
                    default:
                        break;
                }
            }
            return { "FilterListStr": JSON.stringify(FilterList) };
        }

        //事件绑定
        function bindEvents() {
            //新增任务
            $("#btn_Add").on("click", function () {
                openEditWin(WebState.ADD);
            });

            //批量添加任务
            $("#btn_Import_Template").on("click", function () {
                $.ImportExcelTemplate({
                    type: "Task", after: function () {
                        gridTask.reload();
                    }
                });
            });

            //导出所有记录
            $("#btn_Export_All").on("click", function () {
                gridTask.Export("任务列表");
            });

            //导出选中记录
            $("#btn_Export_Select").on("click", function () {
                //获取选中数据
                var datas = gridTask.getSelectedRows();
                if (datas.length > 0) {
                    gridTask.Export("任务列表", datas);
                } else {
                    layer.tips('请选择项', "#btn_Export_Select", {
                        tips: 3
                    });
                }
            });

            //重新加载任务
            $("#btn_refresh").on("click", function () {
                //获取选中数据
                var datas = gridTask.getSelectedRows();
                if (datas.length > 0) {
                    var arrId = [];
                    for (var i = 0; i < datas.length; i++) {
                        arrId.push(datas[i].TaskID);
                    }
                    $.ajax({
                        type: "post",
                        url: "/Task/Reload",
                        contentType: "application/json",
                        data: JSON.stringify(arrId),
                        beforeSend: function () {
                            //加载等待层
                            index = layer.load(0);
                        },
                        complete: function () {
                            layer.close(index);
                        },
                        success: function (data) {
                            if (data.HasError) {
                                layer.alert(data.Message);
                            } else {
                                layer.msg("任务重新加载完成");
                            }
                        }
                    });
                } else {
                    layer.tips('请选择项', "#btn_refresh", {
                        tips: 3
                    });
                }
            });

            //搜索
            $("#btn_search").on("click", function () {
                var paramList = $(".searchbox").getParamList();
                gridTask.load(handleParam(paramList));
            });

            //操作列点击事件
            $("#grid_Task").on("click", "a.action", function () {
                var rowid = $(this).parent().attr("data-index");
                if ($(this).hasClass("action-update")) {
                    //修改
                    openEditWin(WebState.EDIT, rowid);
                } else if ($(this).hasClass("action-enabled")) {
                    //运行任务
                    updateTaskStatus(rowid, 0);
                } else if ($(this).hasClass("action-disabled")) {
                    //停止任务
                    updateTaskStatus(rowid, 1);
                } else if ($(this).hasClass("action-delete")) {
                    //删除
                    delTask(rowid);
                } else if ($(this).hasClass("action-run")) {
                    //立即运行
                    runTask(rowid);
                }
            });
        }

        function runTask(rowid) {
            //立即运行一次任务
            $.ajax({
                type: "get",
                url: "/Task/Run/" + rowid,
                beforeSend: function () {
                    //加载等待层
                    index = layer.load(0);
                },
                complete: function () {
                    layer.close(index);
                },
                success: function (data) {
                    if (data.HasError) {
                        layer.alert(data.Message);
                    } else {
                        layer.msg("执行完成");
                    }
                }
            });
        }

        //打开 新增|编辑 界面
        function openEditWin(mode, rowid) {
            var params = { "mode": mode, id: "" };
            if (mode != WebState.ADD) {
                params.id = rowid;
            }
            layer.open({
                type: 2,
                shift: -1, //禁止弹出时动画效果
                move: false, //禁止窗口移动
                title: WebStateCN[mode] + '任务',
                shade: 0.8,
                area: ['100%', '100%'],
                content: "/Task/Edit?" + decodeURIComponent(jQuery.param(params)),
                end: function () {
                    if (mode != WebState.READ) {
                        gridTask.reload();
                    }
                }
            });
        }

        //删除任务
        function delTask(rowid) {

            Ywdsoft.delConfirm(function () {
                //加载等待层
                var index;
                $.ajax({
                    type: "delete",
                    url: "/Task/" + rowid,
                    dataType: "json",
                    beforeSend: function () {
                        //加载等待层
                        index = layer.load(0);
                    },
                    complete: function () {
                        layer.close(index);
                    },
                    success: function (data) {
                        if (data.HasError) {
                            layer.alert(data.Message);
                        } else {
                            gridTask.reload();
                        }
                    }
                });
            });
        }

        //更新任务状态
        function updateTaskStatus(rowid, status) {
            //加载等待层
            var index;
            $.ajax({
                type: "put",
                url: "/Task/{0}/{1}".format(rowid, status),
                dataType: "json",
                beforeSend: function () {
                    //加载等待层
                    index = layer.load(0);
                },
                complete: function () {
                    layer.close(index);
                },
                success: function (data) {
                    if (data.HasError) {
                        layer.alert(data.Message);
                    } else {
                        gridTask.reload();
                    }
                }
            });
        }
    </script>
}